package 多线程;

import java.util.concurrent.atomic.AtomicIntegerFieldUpdater;
import java.util.concurrent.atomic.AtomicReference;
import java.util.concurrent.atomic.AtomicStampedReference;

/**
 * @Author: 朱胜伟
 * @CreateTime: 2021-02-02 15:19
 * @Description: 对原子整数字段进行更新（对 对象的整数属性 进行原子更新）
 */
public class AtomicIntegerFieldUpdaterTest {

    static AtomicReference<String> atomicReference = new AtomicReference<>("abc");

    static AtomicStampedReference<String> stampedReference = new AtomicStampedReference<>("abc",0);
    public static void main(String[] args) {
        //获取当前版本号
        int j = stampedReference.getStamp();
        stampedReference.compareAndSet("abc","cge",j,j+1);
        for (int i = 0;i < 100; i++){
            new Thread(new Runnable() {
                @Override
                public void run() {
                    if(atomicReference.compareAndSet("abc","def")){
                        System.out.println(Thread.currentThread().getName()+"把字符串abc改为def");
                    }
                }
            }).start();
        }

        for (int i = 0;i < 100; i++){
            new Thread(new Runnable() {
                @Override
                public void run() {
                    if(atomicReference.compareAndSet("def","abc")){
                        System.out.println(Thread.currentThread().getName()+"还原字符串");
                    }
                }
            }).start();
        }
    }
}
class User{
    volatile int age;
    String name;

}
